<?php

namespace App\Exports;

use App\Models\Order;
use App\Models\Qh_Cdkey;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class QhUserExport2 implements  FromCollection, WithStyles
{
    protected array $params;
    public function __construct($params)
    {
        $this->params = $params;
    }

    public function styles(Worksheet $sheet)
    {
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);

        // 设置整个表格的列宽
        for ($i = 1; $i <= $highestColumnIndex; $i++) {
            $sheet->getColumnDimension(Coordinate::stringFromColumnIndex($i))->setWidth(30);
        }

        // 设置整个表格的垂直居中和水平居中
        $sheet->getStyle('A1:'.$highestColumn.$highestRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getStyle('A1:'.$highestColumn.$highestRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

        // 设置整个表格的字体大小
        $sheet->getStyle('A1:'.$highestColumn.$highestRow)->getFont()->setSize(12)->setName('宋体');

        // 设置整个表格的行高
        $sheet->getDefaultRowDimension()->setRowHeight(22);

        // 添加边框样式到所有单元格
        $sheet->getStyle('A1:'.$highestColumn.$highestRow)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);

        return [];
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return new Collection($this->createData());
    }

    public function createData(): array
    {
        $users = $this->params['users'];
        $collect = [
            ['ID', '昵称', '省份', '坚持天数', '手机号', '状态', '注册时间']
        ];

        foreach ($users as $user) {
            $collect[] = [
                $user->id,
                $user->nickname,
                $user->province,
                $user->ksDaysCount,
                $user->mobile ? $user->mobile."\t" : '',
                USER_STATUS[$user->status],
                !empty($user->createtime) ? \Illuminate\Support\Carbon::createFromTimestamp($user->createtime)->format('Y-m-d H:i:s') : '-',
            ];
        }

        return $collect;
    }
}
